﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace QS
{
    class QGrid
    {
        private int m_Width = 100;
        private int m_Height = 100;
        private float m_Factor = 10;

        private VertexBuffer m_VertexBuffer;
        private BasicEffect m_Effect;

        public QGrid(float factor = 1)
        {
            m_Factor = factor;
        }

        public void Load(GraphicsDevice gd, int _width, int _height)
        {
            m_Width = _width;
            m_Height = _height;
            m_VertexBuffer = new VertexBuffer(gd, typeof(VertexPositionColor), (m_Width + 1) * 2 + (m_Height + 1) * 2, BufferUsage.WriteOnly);

            VertexPositionColor[] vertices = new VertexPositionColor[(m_Width + 1) * 2 + (m_Height + 1) * 2];
            
            int i = 0;
            for (int x = -m_Width / 2; x < m_Width / 2 + 1; x++)
            {
                vertices[i++] = new VertexPositionColor(new Vector3(m_Factor * x, 0f, m_Factor * m_Height / 2), Color.Lime);
                vertices[i++] = new VertexPositionColor(new Vector3(m_Factor * x, 0f, m_Factor * -m_Height / 2), Color.Lime);
            }
            for (int z = -m_Height / 2; z < m_Height / 2 + 1; z++)
            {
                vertices[i++] = new VertexPositionColor(new Vector3(m_Factor * -m_Width / 2, 0f, m_Factor * z), Color.Lime);
                vertices[i++] = new VertexPositionColor(new Vector3(m_Factor * m_Width / 2, 0f, m_Factor * z), Color.Lime);
            }

            m_VertexBuffer.SetData<VertexPositionColor>(vertices);

            m_Effect = new BasicEffect(gd);
        }

        public void Draw(GraphicsDevice gd, Matrix view, Matrix proj, Matrix world)
        {
            gd.SetVertexBuffer(m_VertexBuffer);

            m_Effect.World = world;
            m_Effect.View = view;
            m_Effect.Projection = proj;
            m_Effect.VertexColorEnabled = true;

            foreach (EffectPass pass in m_Effect.CurrentTechnique.Passes)
            {
                pass.Apply();
                gd.DrawPrimitives(PrimitiveType.LineList, 0, m_VertexBuffer.VertexCount);
            }
        }
    }
}
